package com.apps.ubc.cc.controller;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.apps.datastore.AccountInformationDatastore;
import com.apps.datastore.dao.AccountObject;
import com.apps.utils.BCryptUtils;

public class ChangePasswordFormController extends HttpServlet {

	private String password;
	private String confirmPassword;
	private AccountInformationDatastore d = new AccountInformationDatastore();

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		password=req.getParameter("password");
		confirmPassword=req.getParameter("confirm");
		Cookie[] cookies= req.getCookies();
		String user = null;
		for(int i = 0; i < cookies.length; i++) {
			if(cookies[i].getName().equals("user"))
				user = cookies[i].getValue();		
		}
		
		if(user == null)
			resp.sendRedirect("/debug.jsp?msg=pref_updated_failed");
		else if(password.equals(confirmPassword)){
			AccountObject lao=d.getAccountObject(user);
			//Username should exist cause user is logged in, but to be safe.
			if(lao != null){
				String hashed = BCryptUtils.hashpw(password, BCryptUtils.gensalt());
				lao.setPassword(hashed);
				d.updateAccountObject(lao);
				//SUCCESS
				resp.sendRedirect("/debug.jsp?msg=pref_updated_sucess");
				
			}
		}else{
			//Password and cofirm are not the same
			resp.sendRedirect("/debug.jsp?msg=pref_updated_failed");
		}

		
		}
		
		
		
}
